$.fn.deserialize = function(d,config) {
	var data= d;
	me  = this;

	if (d === undefined) {
		return me;
	}

	config = $.extend({ isPHPnaming	: false,
						overwrite	: true},config);
	
	if (d.constructor == Array)	{
		data={};
		for(var i=0; i<d.length; i++) {
			if (typeof data[d[i].name] != 'undefined') {
				if (data[d[i].name].constructor!= Array) {
					data[d[i].name]=[data[d[i].name],d[i].value];
				} else {
					data[d[i].name].push(d[i].value);
				}
			} else {
				data[d[i].name]=d[i].value;
			}
		}
	}

	// now data is a hash. insert each parameter into the form
	$('input,select,textarea',me)
	.each(function() {
			  var p=this.name;
			  var v = [];
			  
			  // handle wierd PHP names if required
			  if (config.isPHPnaming) {
				  p=p.replace(/\[\]$/,'');
			  }
			  if(p && data[p] != undefined) {
				  v = data[p].constructor == Array ? data[p] : [data[p]];
			  }
			  // Additional parameter overwrite
			  if (config.overwrite === true || data[p]) {
				  switch(this.type || this.tagName.toLowerCase()) {
				  case "radio":
				  case "checkbox":
					  this.checked=false;
					  for(var i=0;i<v.length;i++) {
						  this.checked|=(this.value!='' && v[i]==this.value);
					  }
					  break;
				  case "select-multiple" || "select":
					  for( i=0;i<this.options.length;i++) {
						  this.options[i].selected=false;
						  for(var j=0;j<v.length;j++) {
							  this.options[i].selected|=(this.options[i].value!='' && this.options[i].value==v[j]);
						  }
					  }
					  break;
				  case "button":
				  case "submit":
					  this.value=v.length>0?v.join(','):this.value;
						  break;
				  default:
					  this.value=v.join(',');
				  }
				  $(this).trigger('change');
			  }
		  });
	return me;
};

jQuery.fn.zenimages = function(options) {
	   var settings = jQuery.extend({
	        multiple: true,
			urlUpload:'/backend/images/admin/upload/',
			urlCancel:'/backend/images/admin/cancel/',
			urlLoad:'/backend/images/admin/load/',
			urlUpdate:'/backend/images/admin/update/',
			use_crop:false,
			crop_width:'',
			crop_height:'',
	        maxConnections: 3,
	        allowedExtensions: ['png','jpg','gif','jpeg'],               
	        sizeLimit: 0,   
	        minSizeLimit: 0,
	        multiple:true
	   }, options);

			
	   		if (!$('#crop_form').length) {
				var crop_panel=$('<div>').attr('id','crop_form').attr('title',"Параметры изображения");
				var forma=$('<form>').attr('id','qq_editor_form');
				
			
				{//using crop
					crop_panel.append('<div id="cropping_panel"><div style="float:left;margin-right:50px;"><div id="crop_selector" style="position:relative;"></div><img id="crop_norm" style="width:400px;" src="" alt="" /></div><div id="qq_crop_preview" style="loat:left;overflow:hidden;"><img alt="" src="" /></div></div><br class="clear"/>');
					var elmnts='<input type="hidden" name="crop" id="crop"/><input type="hidden" name="crop_width" id="crop_width"/><input type="hidden" name="crop_height" id="crop_height"/><input type="hidden" name="crop_x" id="crop_x"/><input type="hidden" name="crop_y" id="crop_y"/>';
					forma.append(elmnts);
				}

				//using alt
				var altinput='<label for="alt">Описание изображения</label><br/><textarea name="alt" class="zend_text_area"></textarea>';
				forma.append(altinput);
				crop_panel.append(forma);		
				
				$('body').append(crop_panel);
				$("#crop_form").dialog({
					resizable : true,
					autoOpen : false,
					width : '50%',
					height:500,
					position:top,
					
					modal : true,
					buttons : {
						'Отмена' : function() {
							$(this).dialog('close');
						},
						'Сохранить': function(){
							$(this).find('form').submit();
						}
					},
					close : function() {
						//$('#crop_selector').css('display','none');
					},
					open: function() {
					}
				});

			}
				
			
			
	   
	   $(this).each( function() {
		   $(this).hide();
		   initUploadPanel($(this));
		   $(this).closest('form').bind('reset',function(){
			   load_images($(this));
		   });
		   
		   $(this).bind('change',function(){
			   load_images($(this));
		   });
		   if($(this).val!=""){
			   $(this).trigger('change');
		   }
	       return($(this));
	    });
	   var uploader_panel_id;

	   function explode(delimiter, string) { // Split a string by string
			var emptyArray = {
				0 : ''
			};

			if (arguments.length != 2 || typeof arguments[0] == 'undefined'
					|| typeof arguments[1] == 'undefined') {
				return null;
			}

			if (delimiter === '' || delimiter === false || delimiter === null) {
				return false;
			}

			if (typeof delimiter == 'function' || typeof delimiter == 'object'
					|| typeof string == 'function' || typeof string == 'object') {
				return emptyArray;
			}

			if (delimiter === true) {
				delimiter = '1';
			}

			return string.toString().split(delimiter.toString());
		}

	   function hide_panel(){
			$('.cpan').hide();
	   } 

		function load_images(inputElement){
			
			$('#'+uploader_panel_id+' li').remove();
			var serialized=inputElement.val();
			if(serialized!=''){
				var loadImages=explode(',',serialized);
				var img="";
				for (i in loadImages)
				{
					if((loadImages[i]!="")&&(!$('#'+loadImages[i]).length))
					{
							var imId=loadImages[i];
							$.ajax({
								  type: 'POST',
								  url: settings['urlLoad'],
								  data: {
										id:imId
								   },
								  dataType: 'json',
								  async:false,
								  beforeSend:function(){
									  var li=$('<li>').attr('id',loadImages[i]).addClass('ui-state-default').addClass('ui-corner-all').html('<span class="qq-upload-spinner"></span>');
									  $('#'+uploader_panel_id+' ul').append(li);
									  if(settings['multiple']==false){
										  $('#'+uploader_panel_id+' .qq-upload-button').hide();
									  }
									  return true;
								  },
								  success: function(data){
										if(data['success']==true){
											
											$('<img>').attr('src',data.thumb_url).bind('load readystatechange',function(){
												$('#qu'+data['id']).html('').css('background-image','url('+data.thumb_url+')').addClass('qq-upload-img').addClass('qq-upload-success');
							
											}).bind('error',function(){
												alert('Соединение с сервером было разорвано,обновите страницу');
											});
										}else{
											$('#qu'+data['id']).html('').addClass('qq-upload-err').addClass('qq-upload-success').addClass('qq-upload-error');
											 if(settings['multiple']==false){
												  $('#'+uploader_panel_id+' .qq-upload-button').show();
											  }	
											 
										}
								  },
								  error:function(){
									  if(settings['multiple']==false){
										  $('#'+uploader_panel_id+' .qq-upload-button').show();
									  }
									  alert('Соединение с сервером было разорвано,обновите страницу');
									  
								  }
								  
								});
					}
				}	
			}
		
		}	
	   

	   function showpanel(el) {
			if (!el.find('.cpan').length) {
				image_panel = "<div class='cpan'><a href='#' class='ui-corner-all ui-state-default button qq_image_delete' title='Удалить изображение'><span class='ui-icon ui-icon-trash'></span></a><a href='#' class='ui-corner-all ui-state-default button qq_imageeditor' title='Редактировать параметры изображения'><span class='ui-icon ui-icon-image'></span></a></div>";
				el.append(image_panel);
			}else{
				el.find('.cpan').show();
			}
	   }

	   function serialized(uploader_panel_id){
		   var serialized=[];
		   $count=0;
		   $('#'+uploader_panel_id).find('li').each(function(){
			   
				id=$(this).attr('id');
				if((typeof(id)!='undefined')&&(id!='')){
					serialized[$count]=id;
				}
				$count++;
		   });
		   return (serialized.join(','));
	   }

	   function preview(img, selection) {
		    if (!selection.width || !selection.height)
		        return;
		    
		    var imagewidth=$('#qq_crop_preview').width();
		    var imageheight=$('#qq_crop_preview').height();
		    
		    
		    var scaleX = imagewidth/selection.width;
		    var scaleY = imageheight/selection.height;
		    
		    var perc_x=Math.floor((selection.x1/$('#crop_norm').width())*100);
		    var perc_y=Math.floor((selection.y1/$('#crop_norm').height())*100);
		    var perc_width=Math.floor((selection.width/$('#crop_norm').width())*100);
		    var perc_height=Math.floor((selection.height/$('#crop_norm').height())*100);
		    
		    $('#qq_crop_preview img').css({
		        width: Math.round(scaleX * $('#crop_norm').width()),
		        height: Math.round(scaleY * $('#crop_norm').height()),
		        marginLeft: -Math.round(scaleX * selection.x1),
		        marginTop: -Math.round(scaleY * selection.y1)
		    });
		
		    var crop='{"crop_x":'+selection.x1
		    		  +',"crop_y":'+selection.y1
		    		  +',"crop_width":'+selection.width
		    		  +',"crop_height":'+selection.height
		    		  +',"perc_x":'+perc_x
		    		  +',"perc_y":'+perc_y
		    		  +',"perc_width":'+perc_width
		    		  +',"perc_height":'+perc_height
		    		  +'}';
		    $('#crop').val(crop);
		}
	   

	   function showimageeditor(el){
			if(!settings.use_crop){
				$('#qq_crop_preview').hide();
			}else{
				$('#qq_crop_preview').show();
			}

			var id = el.closest('li').attr('id');


			
			var ias=$('#crop_norm').imgAreaSelect({
				handles: true,
				instance: true,
				persistent:true,
				parent:$('#crop_selector'),
				fadeSpeed: 200,
				onSelectChange: preview
			});	
			
			$.ajax({
				  url: settings['urlLoad'],
				  data:{id:id},
				  dataType:'json',
				  async:false,
				  success: function(data){
					  if(data['success']==true){
						  
					  $('#crop_form form').deserialize(data);
						
						$('#crop_form form').ajaxForm({
							dataType : 'json',
							success : function(){
							$("#crop_form").dialog('close');
							},
							iframe : true,
							data:{id:id},
							url : settings['urlUpdate']
						});
						$('<img>').attr('src',data['img_url']).bind('load readystatechange',function(){
							$("#crop_form img").attr('src',data['img_url']);
							$("#crop_form").dialog('open');
							
							if(settings['use_crop']!=false){
								
									ias.update();
									
									var crop_width=0;
									
									
									
									if(typeof(settings['crop_width'])=='number'){
										crop_width=settings['crop_width'];
									}else{
										if(typeof(settings['crop_width'])=='object'){
											crop_width=settings['crop_width'].val();
										}
										if(typeof(settings['crop_width'])=='string'){
											crop_width=$(settings['crop_width']).val();
										}
										
									}
									
									var crop_height=0;
									if(typeof(settings['crop_height'])=='number'){
										crop_height=settings['crop_height'];
									}else{
										if(typeof(settings['crop_height'])=='object'){
											crop_height=settings['crop_height'].val();
										}
										if(typeof(settings['crop_height'])=='string'){
											crop_height=$(settings['crop_height']).val();
										}
									}
									
							
							if((crop_width>0)&&(crop_height>0)){
								var aspect=crop_width+":"+crop_height;
								scale=Math.floor(crop_width/crop_height);
								ias.setOptions({aspectRatio: aspect}); 
								ias.setOptions({minHeight: 50,minWidth:50*scale});
								
								$('#qq_crop_preview').css('width',crop_width+'px').css('height',crop_height+'px');
								
								if($('#crop').val()!=""){
									var params=$.parseJSON($('#crop').val());
								}
								else{
									var params={};
									params.crop_x=0;
									params.crop_y=0;
									params.crop_height=parseInt(crop_height);
									params.crop_width=parseInt(crop_width);
								}
								if((params.crop_width >=1)&&(params.crop_height >=1)){
									
									var x2=params.crop_x+params.crop_width;
									var y2=params.crop_y+params.crop_height;
									var w=$('#crop_norm').width();
									var h=$('#crop_norm').height();
									
									if(x2>w){
										x2=w;
									}
									
									if(y2>h){
										y2=h;
									}
									
									
									
									ias.setOptions({ x1: params.crop_x,x2:x2,y1: params.crop_y,y2:y2});
									preview($('#crop_norm'),ias.getSelection());
								}else{
									alert('50');			
									ias.setOptions({ x1: 0,x2:50,y1: 0,y2:50*scale});
									preview($('#crop_norm'),ias.getSelection());
								}
							}else{
								$('#cropping_panel').hide();
							}		
							
							}
							
						}).bind('error',function(){
							alert('Соединение с сервером было разорвано');
						});
						
						
						
					}else{
						alert('Изображение было удалено с сервера,обратитесь к администратору или в техподдержку');
					}
				  }
				});
		
			
			
			
			
		}
	   
	   function initUploadPanel(inputElement){
		   var id=inputElement.attr('id');
		   
		   
		   
		   
		   
		   
		   
		   
		   uploader_panel_id='uploader_'+id;
  		   //inputElement.hide();
		   inputElement.after('<div id="'+uploader_panel_id+'" class="zenimages clearfix"></div>');

		   //create uploader element
		   var uploader=new qq.FileUploader({
			    multiple : settings['multiple'],
				action : settings['urlUpload'],
				element:document.getElementById(uploader_panel_id),
				allowedExtensions:settings['allowedExtensions'],
				template: '<div class="qq-uploader">' + 
				'<ul class="qq-upload-list"></ul>' +
			    '<div class="qq-upload-button ui-state-default ui-corner-all button"><div class="qq-upload-drop-area ui-state-default ui-corner-all"><span></span></div>Загрузить файлы</div>' +
			 	'</div>',

			    fileTemplate: '<li class="ui-state-default ui-corner-all">'+
			    '<span class="qq-upload-file"></span>'+
			    '<span class="qq-upload-spinner"></span>'+
			    '<span class="qq-upload-size"></span>'+
			    '<a class="qq-upload-cancel" href="#">Отмена</a>'+
			    '<span class="qq-upload-failed-text ui-state-error ui-corner-all">Ошибка</span>'+
				'</li>',        
				onSubmit: function(id, fileName){
					$('#'+uploader_panel_id+' .qq-upload-fail').remove();
					 if(settings['multiple']==false){
						  $('#'+uploader_panel_id+' .qq-upload-button').hide();
					  }
				},
				onCancel: function(id, fileName){
					$.post(settings['urlCancel'], {
						file:fileName
					});
					 if(settings['multiple']==false){
						  $('#'+uploader_panel_id+' .qq-upload-button').show();
					  }
					return(true);
				},
				onComplete: function(id, fileName, responseJSON){
				if (responseJSON) {
					var n=id+1;
					el=$(uploader._getItemByFileId(id));
					
					if (typeof(responseJSON.errors )!= "undefined") {
						var str="";
						var errors = responseJSON.errors;
						for (i in errors) {
							str += '<span>' + errors[i] + '</span>';
						}
							el.find('#uploader_panel_id .qq-upload-failed-text').html(str);
					}
					
					if (typeof(responseJSON.thumb_url) != "undefined") {
							el.css('background-image','url('+responseJSON.thumb_url+')').addClass('qq-upload-img');
							el.find('span').hide();
							el.attr('id','qu'+responseJSON.id);
							 //Если мультизагрузка отключена, прячем кнопку загрузчика
							  if(settings['multiple']==false){
								  $('#'+uploader_panel_id+' .qq-upload-button').hide();
							  }
							inputElement.val(serialized(uploader_panel_id));
						}
				} 
					
				},
				messages: {
			        typeError: "Файл {file} имеет неверное расширение. Только файлы с разрешениями {extensions} разрешены.",
			        sizeError: "Файл {file} слишком большой, максимальный размер {sizeLimit}.",
			        minSizeError: "Файл {file} слишком маленький , минимальный размер {minSizeLimit}.",
			        emptyError: "Файл {file} пустой, выберите файлы снова,но без него.",
			        onLeave: "Файлы загружаются на сервер, если вы уйдете прогресс не будет сохранён."            
			    }
			});

		   //make uploader list sortable
		  $('#'+uploader_panel_id+' .qq-upload-list').sortable({
				placeholder : 'ui-state-highlight',
				opacity : 0.6,
				tolerance : 'pointer',

				start : function(event, ui) {
					hide_panel();
				},
				stop : function() {

				},
				update : function(event, ui) {
					inputElement.val(serialized(uploader_panel_id));
				}
			});


			// init panel events

			$('#'+uploader_panel_id+' .qq-upload-success').live('mouseenter',function(){
				showpanel($(this));
			}).live('mouseleave',function(){
				hide_panel();
			});


			$('#'+uploader_panel_id+' .qq_image_delete').live('click',function(){
				hide_panel();
				$(this).closest('li').animate({width:0,height:0,opacity:0},
					600,
					function(){
						$(this).remove();
						inputElement.val(serialized(uploader_panel_id));
						 //Если мультизагрузка отключена, показываем кнопку загрузчика
						  if(settings['multiple']==false){
							  $('#'+uploader_panel_id+' .qq-upload-button').show();
						  }
					}
				);
				return false;
			});

			$('#'+uploader_panel_id+' .qq_imageeditor').live('click',function(){
				hide_panel();
				showimageeditor($(this));
				return false;
			});
			

		 }
};





